<template>
    <div class="chat-sidebar-content" ref="chatSidebarListRef">
        <template v-if="pinnedList.length > 0">
            <div class="sidebar-title">已置顶</div>
            <div class="chat-list mb-20">
                <div class="chat-item" v-for="item in groupedPinnedList" :key="item">
                    <div class="time">{{ item.time }}</div>
                    <div v-for="chat in item.list" :key="chat.id" class="item"
                        :class="{ active: chat.id == props.activeChatId }">
                        <div class="name" @click="handleSelect(chat)">{{ chat.name }}</div>
                        <ConversationAction ref="conversationActionRef" v-if="!chat.id.startsWith('temp_')"
                            :pinned="true" :chat="chat" @pin="handlePin" @edit="handleEdit" @delete="handleDelete" />
                    </div>
                </div>
            </div>
        </template>
        <template v-if="conversList.length > 0">
            <div class="sidebar-title">会话列表</div>
            <div class="chat-list">
                <div class="chat-item" v-for="item in groupedConversList" :key="item">
                    <div class="time">{{ item.time }}</div>
                    <div v-for="chat in item.list" :key="chat.id" class="item"
                        :class="{ active: chat.id == props.activeChatId }">
                        <div class="name" @click="handleSelect(chat)">{{ chat.name }}</div>
                        <ConversationAction ref="conversationActionRef" v-if="!chat.id.startsWith('temp_')"
                            :pinned="false" :chat="chat" @pin="handlePin" @edit="handleEdit" @delete="handleDelete" />
                    </div>
                </div>
            </div>
        </template>
    </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, watch, toRefs } from "vue";
import ConversationAction from './ConversationAction.vue'
const { proxy } = getCurrentInstance()
const emit = defineEmits(['select', "pin", "edit", "delete"])
const props = defineProps({
    conversList: {
        type: Array,
        default: () => []
    },
    pinnedList: {
        type: Array,
        default: () => []
    },
    activeChatId: {
        type: String,
        default: ''
    }
})

const handleSelect = (chat) => {
    emit('select', chat);
}

const handleTime = (list) => {
    if (!list || list.length === 0) return [];
    const dateMap = new Map();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    list.forEach(item => {
        if (!item.created_at) return;

        // 处理10位时间戳（秒级），转换为13位时间戳（毫秒级）
        let timestamp = item.created_at;
        if (typeof timestamp === 'number' && timestamp.toString().length === 10) {
            timestamp = timestamp * 1000;
        }

        const date = new Date(timestamp);
        const dateKey = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        const dateStr = dateKey.getTime().toString();
        if (!dateMap.has(dateStr)) {
            dateMap.set(dateStr, []);
        }
        dateMap.get(dateStr).push(item);
    });
    const result = [];
    dateMap.forEach((items, dateStr) => {
        const date = new Date(parseInt(dateStr));
        let timeTitle = '';
        const compareDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        if (compareDate.getTime() === today.getTime()) {
            timeTitle = '今天';
        } else {
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            if (year === today.getFullYear()) {
                timeTitle = `${month}月${day}日`;
            } else {
                const shortYear = year.toString().slice(2);
                timeTitle = `${shortYear}年${month}月${day}日`;
            }
        }

        result.push({
            time: timeTitle,
            date: date,
            list: items
        });
    });

    // 按日期降序排序（最新的日期在前）
    result.sort((a, b) => b.date.getTime() - a.date.getTime());
    return result;
}

const groupedConversList = computed(() => {
    return handleTime(props.conversList);
});

const groupedPinnedList = computed(() => {
    return handleTime(props.pinnedList);
});

/** 置顶会话 */
const handlePin = (chat) => {
    emit("pin", chat);
}

/** 编辑会话名称 */
const handleEdit = (chat) => {
    emit("edit", chat);
}

/** 删除会话 */
const handleDelete = (chat) => {
    emit("delete", chat);
}

const chatSidebarListRef = ref(null);
const conversationActionRef = ref(null);
// 滚动时关闭所有操作弹窗
const handleSidebarScroll = () => {
    const refs = conversationActionRef.value;
    if (!refs) return;
    if (Array.isArray(refs)) {
        refs.forEach(r => r?.hide && r.hide());
    } else {
        refs?.hide && refs.hide();
    }
};

onMounted(() => {
    const el = chatSidebarListRef.value;
    if (el) {
        el.addEventListener('scroll', handleSidebarScroll, { passive: true });
    }
});

onBeforeUnmount(() => {
    const el = chatSidebarListRef.value;
    if (el) {
        el.removeEventListener('scroll', handleSidebarScroll);
    }
});


</script>
<style lang="scss">
.chat-sidebar-content {
    flex: 1;
    overflow-y: auto;

    .sidebar-title {
        color: #333333;
        font-weight: 600;
    }

    .chat-list {
        margin-top: 8px;
        padding-right: 5px;
        .chat-item {
            margin-bottom: 15px;

            .time {
                color: #666666;
                margin-bottom: 5px;
            }

            .item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-right: 5px;
                cursor: pointer;
                transition: all 0.2s;
                position: relative;
                border-radius: 5px;
                margin-bottom: 5px;
                font-weight: 400;
                height: 35px;
                color: #333333;

                &:hover {
                    background: #F0F0F0 !important;

                    .action {
                        opacity: 1;
                    }
                }

                &.active {
                    background: #E5EEFE !important;
                    color: #045CFE;
                    font-weight: 600;

                    .action {
                        color: #045CFE;
                        background: #dde8fc;

                        &:hover {
                            background: rgba(213, 226, 248, 0.33);
                        }
                    }
                }

                .name {
                    flex: 1;
                    width: 100px;
                    padding: 8px 5px 8px 10px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .action {
                    opacity: 0;
                    color: #333;
                    width: 30px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 28px;
                    border-radius: 6px;
                    cursor: pointer;

                    &:hover {
                        background: rgba(213, 226, 248, 0.33);
                    }

                }

                .action:focus,
                .action:hover {
                    background: rgba(213, 226, 248, 0.33);
                    opacity: 1;
                }
            }
        }
    }
}
</style>